import { compose } from './compose';

/**
 * 在applyMiddleware中改变dispatch
 */

// export const applyMiddleware = (store, ...middlewares) => {
//   middlewares.reverse();
//   middlewares.forEach(middleware => {
//     store.dispatch = middleware(store);
//   })
// }

/**
 * 使用组合函数compose优化
 */
export const applyMiddleware = (...midddlewares) => {
  return (createStore) => (...args) => {
    const store = createStore(...args);
    let dispatch = () => { };
    
    const middlewareAPI = {
      getState: store.getState,
      dispatch: (...args) => dispatch(...args)
    };
    const chain = midddlewares.map((middleware) => middleware(middlewareAPI));
    dispatch = compose(...chain)(store.dispatch);

    return {
      ...store,
      dispatch
    }
  }
}